package com.crm.utils;

import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.ResourceUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * 获取客户端信息的工具
 */
public class NetworkUtil {

    /**
     * 获取 ip 地址
     *
     * @return ip
     */
    public static String getIp() {
        String ip = "127.0.0.1";
        try {
            URL url = new URL("http://checkip.amazonaws.com");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            ip = in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ip;
    }

    /**
     * 获取格式ip地址
     */
    public static String getIpAddress() {
        String region = "";
        try {
            // 1、创建 searcher 对象
            File file = ResourceUtils.getFile("classpath:ip2region.xdb");
            String dbPath = file.getPath();
            Searcher searcher = Searcher.newWithFileOnly(dbPath);
            // 2、查询
            long sTime = System.nanoTime();
            region = searcher.search(NetworkUtil.getIp());
            long cost = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - sTime);
            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return region;
    }

    /**
     * 获取省份
     *
     * @return 省份
     */
    public static String getProvince() {
        String province = null;
        try {
            String str = NetworkUtil.getIpAddress();
            String a = str.substring(0, str.lastIndexOf("|"));
            String b = a.substring(0, a.lastIndexOf("|"));
            province = b.substring(b.lastIndexOf("|") + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return province;
    }


    /**
     * 获取城市
     *
     * @return 城市
     */
    public static String getCity() {
        String city = null;
        try {
            String str = NetworkUtil.getIpAddress();
            String a = str.substring(0, str.lastIndexOf("|"));
            city = a.substring(a.lastIndexOf("|") + 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return city;
    }


    public static void main(String[] args) {
        System.out.println(getCity());
    }

}
